package com.itlxd.controller;


import com.itlxd.entity.User;
import com.itlxd.exception.LoginException;
import com.itlxd.global.ErrorCode;
import com.itlxd.global.SysConstants;
import com.itlxd.global.SysMessages;
import com.itlxd.result.ResultVO;
import com.itlxd.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-12-25
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("login")
    public ResultVO<User> login(@RequestBody User user, HttpSession session) {
        boolean exist = userService.validateCode(user.getPhone(), user.getCode());
        if (!exist) {
            return ResultVO.error(SysMessages.CODE_IS_ERROR);
        }
        User loginUser = userService.getUser(user);

        if (null == loginUser) {
            userService.addSave(user);
            session.setAttribute(SysMessages.LOGIN_USER, user);
            return ResultVO.success(user, SysMessages.QUERY_SUCCESS);
        }

        session.setAttribute(SysMessages.LOGIN_USER, loginUser);
        return ResultVO.success(loginUser, SysMessages.QUERY_SUCCESS);
    }

    @PostMapping("/loginout")
    public ResultVO<User> loginOut(HttpSession session) {
        session.removeAttribute(SysConstants.LOGIN_USER);
        return ResultVO.success(SysMessages.LOGOUT_SUCCESS);
    }

    @GetMapping("/getCode")
    public ResultVO<Integer> getCode(@RequestParam String phone) {
        Integer code = userService.generateCode(phone);
        return ResultVO.success(code, SysMessages.GENERATE_CODE_SUCCESS);
    }
}

